import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sp_util/sp_util.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:xiongmao_clean_flutter_module/util/toast_utils.dart';
import '../../res/gaps.dart';
import '../res/colors.dart';
import '../res/constant.dart';
import '../widgets/load_image.dart';
import 'loading_util.dart';
import 'log_utils.dart';

class CommonUtils {
  static String toFormattedString(year,month,day) {
    String yyyy = year?.toString().padLeft(4, '0') ?? '0000';
    String mm = month?.toString().padLeft(2, '0') ?? '00';
    String dd = day?.toString().padLeft(2, '0') ?? '00';
    MyLog.e("msg==111======"+'$yyyy-$mm-$dd');
    return '$yyyy-$mm-$dd';
  }

  static double getScreenWidth(context) {
    MediaQueryData mediaQuery = MediaQuery.of(context);
    return mediaQuery.size.width;
  }

  static double getScreenHeight(context) {
    MediaQueryData mediaQuery = MediaQuery.of(context);
    return mediaQuery.size.height;
  }


  static String? getMyUserAgent() {
    // var platformVersion = "";
    // try {
    //   platformVersion = FkUserAgent.userAgent!;
    //   print(platformVersion);
    // } on PlatformException {
    //   platformVersion = 'Failed to get platform version.';
    // }
    var s = "XmjzCapp/" + (SpUtil.getString(Constant.versionName)??"") + " ";
    MyLog.e("msg---userAgent---"+s);
    return s;
    // return "XmjzCapp/6.7.5 Mozilla/5.0 (Linux; Android 14; 23113RKC6C Build/UKQ1.230804.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/118.0.0.0 Mobile Safari/537.36 AgentWeb/4.1.9  UCBrowser/11.6.4.950";
  }

  static const signsEn = [
    {'name': 'Aquarius', 'start': '01-20', 'end': '02-18'},
    {'name': 'Pisces', 'start': '02-19', 'end': '03-20'},
    {'name': 'Aries', 'start': '03-21', 'end': '04-19'},
    {'name': 'Taurus', 'start': '04-20', 'end': '05-20'},
    {'name': 'Gemini', 'start': '05-21', 'end': '06-21'},
    {'name': 'Cancer', 'start': '06-22', 'end': '07-22'},
    {'name': 'Leo', 'start': '07-23', 'end': '08-22'},
    {'name': 'virgo', 'start': '08-23', 'end': '09-22'},
    {'name': 'Libra', 'start': '09-23', 'end': '10-23'},
    {'name': 'Scorpio', 'start': '10-24', 'end': '11-22'},
    {'name': 'Sagittarius', 'start': '11-23', 'end': '12-21'},
    {'name': 'Capricorn', 'start': '12-22', 'end': '01-19'},
  ];

  static const signs = [
    {'name': '水瓶座', 'start': '01-20', 'end': '02-18'},
    {'name': '雙魚座', 'start': '02-19', 'end': '03-20'},
    {'name': '白羊座', 'start': '03-21', 'end': '04-19'},
    {'name': '金牛座', 'start': '04-20', 'end': '05-20'},
    {'name': '雙子座', 'start': '05-21', 'end': '06-21'},
    {'name': '巨蟹座', 'start': '06-22', 'end': '07-22'},
    {'name': '獅子座', 'start': '07-23', 'end': '08-22'},
    {'name': '處女座', 'start': '08-23', 'end': '09-22'},
    {'name': '天秤座', 'start': '09-23', 'end': '10-23'},
    {'name': '天蠍座', 'start': '10-24', 'end': '11-22'},
    {'name': '射手座', 'start': '11-23', 'end': '12-21'},
    {'name': '摩蠍座', 'start': '12-22', 'end': '01-19'},
  ];

  static String? getZodiac(int month, int day) {
    var signs = CommonUtils.signs;
    final sign = signs[month - 1];
    final start = DateTime.parse('2000-${sign['start']}');
    final end = DateTime.parse('2000-${sign['end']}');
    final birthday = DateTime(2000, month, day);
    if (birthday.isBefore(start)) {
      return signs[month - 2 < 0 ? 11 : month - 2]['name'];
    } else if (birthday.isAfter(end)) {
      return signs[month % 12]['name'];
    } else {
      return sign['name'];
    }
  }

  static saveBytesImageToGallery(Uint8List pngBytes) async {
    // 获取应用程序的临时目录
    Directory tempDir = await getTemporaryDirectory();
    // 将Uint8List保存为文件
    File file = File('${tempDir.path}/image.png');
    await file.writeAsBytes(pngBytes);
    // 将文件保存到手机相册中
    final result = await ImageGallerySaver.saveFile(file.path);
    Toast.show("Image saved successfully");
    print(result);
  }

  static saveNetworkImage(String url) async {
    var response = await Dio()
        .get(url, options: Options(responseType: ResponseType.bytes));
    final result = await ImageGallerySaver.saveImage(
        Uint8List.fromList(response.data),
        quality: 60);
    Toast.show("Operation Successful");
    print(result);
  }

  static String formatCount(String count) {
    int? auditCount = int.tryParse(count);
    if (auditCount != null && auditCount > 99) {
      return '99+';
    } else {
      return count;
    }
  }

  static String formatPrice(String price,
      {MoneyFormat format = MoneyFormat.END_INTEGER}) {
    return MoneyUtil.changeYWithUnit(
        NumUtil.getDoubleByValueStr(price) ?? 0, MoneyUnit.YUAN,
        format: format);
  }

  static void getAndroidVersion() async {
    AndroidDeviceInfo androidInfo;
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    if (Platform.isAndroid) {
      androidInfo = await deviceInfo.androidInfo;
      String version = androidInfo.version.release;
      print('Android 版本：$version');
    }
  }

  static Future<String> getVersionName() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    // String appName = packageInfo.appName;
    // String packageName = packageInfo.packageName;
    String version = packageInfo.version;
    // String buildNumber = packageInfo.buildNumber;
    return version;
  }
  //
  // /// 打开链接
  // static Future<void> launchWebURL(String url) async {
  //   final Uri uri = Uri.parse(url);
  //   if (await canLaunchUrl(uri)) {
  //     await launchUrl(uri);
  //   } else {
  //     Toast.show('打开链接失败！');
  //   }
  // }
  //

  /// 打开内部链接
  // static Future<void> launchInAppWebView(String url) async {
  //   final Uri uri = Uri.parse(url);
  //   await launchUrl(uri,mode: LaunchMode.inAppWebView);
  //   // if (await canLaunchUrl(uri)) {
  //   //   MyLog.e("msg---canLaunchUrl----");
  //   //   await launchUrl(uri,mode: LaunchMode.externalApplication);
  //   // } else {
  //   //   Toast.show('打开链接失败！');
  //   // }
  // }

  /// 打开外部链接
  // static Future<void> launchBrowserURL(String url) async {
  //   final Uri uri = Uri.parse(url);
  //   await launchUrl(uri,mode: LaunchMode.externalApplication);
  //   // if (await canLaunchUrl(uri)) {
  //   //   MyLog.e("msg---canLaunchUrl----");
  //   //   await launchUrl(uri,mode: LaunchMode.externalApplication);
  //   // } else {
  //   //   Toast.show('打开链接失败！');
  //   // }
  // }


  /// 调起拨号页
  // static Future<void> launchTelURL(String phone) async {
  //   final Uri uri = Uri.parse('tel:$phone');
  //   if (await canLaunchUrl(uri)) {
  //     await launchUrl(uri);
  //   } else {
  //     Toast.show('拨号失败！');
  //   }
  // }

  // static void callMobile(String areaCode, String mobile) {
  //   if(mobile==""){
  //     Toast.show(S.of(Get.context!).no_phone);
  //     return;
  //   }
  //   launch("tel:" + areaCode + mobile);
  // }

  static void showGeneralDialogOneBtn(
      String msg,
      {String title = "",
        VoidCallback? callBack,
        Widget? contentWidget,
        String btnNotice = ""}) {
    if (title == "") {
      title = "Tips";
    }
    if (btnNotice == "") {
      btnNotice = "I see.";
    }
    showDialog(
        context: Get.context!,
        builder: (context) {
          return AlertDialog(
              title: Text(title),
              content: SingleChildScrollView(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      msg,
                    ),
                    contentWidget ?? Gaps.empty
                  ],
                ),
              ),
              actions: [
                TextButton(
                    child: Text(btnNotice,style: TextStyle(fontSize: 18)),
                    onPressed: () {
                      Navigator.of(context).pop();
                      callBack?.call();
                    }),
              ]);
        });
  }

  static void showGeneralDialog(
      String msg, VoidCallback negativeCallBack, VoidCallback positiveCallBack,
      {String title = "",
      Widget? contentWidget,
      String negativeNotice = "",
      String positiveNotice = ""}) {
    if (title == "") {
      title = "提示";
    }
    if (negativeNotice == "") {
      negativeNotice = "取消";
    }
    if (positiveNotice == "") {
      positiveNotice = "确定";
    }
    showDialog(
        context: Get.context!,
        builder: (context) {
          return AlertDialog(
              surfaceTintColor:Colours.white,
              title: Text(title),
              content: SingleChildScrollView(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      msg,
                    ),
                    contentWidget ?? Gaps.empty
                  ],
                ),
              ),
              actions: [
                TextButton(
                    child: Text(negativeNotice,style: TextStyle(fontSize: 18)),
                    onPressed: () {
                      Navigator.of(context).pop();
                      negativeCallBack.call();
                    }),
                TextButton(
                    child: Text(positiveNotice,style: TextStyle(fontSize: 18)),
                    onPressed: () {
                      Navigator.of(context).pop();
                      positiveCallBack.call();
                    })
              ]);
        });
  }

  static String getAgeByBirthYear(String birthYear) {
    try {
      var parse = int.parse(birthYear);
      final now = DateTime.now();
      final age = now.year - parse;
      return age.toString();
    } catch (e) {
      return "";
    }
  }

  static getSimpleText(data,int fontSize,color,{fontWeight = FontWeight.normal,TextAlign? textAlign,double? height,int? maxLines,bool? softWrap,TextOverflow? overflow}) {
    return Text(data??"",style: TextStyle(fontSize:double.parse(fontSize.toString()) ,color: color,fontWeight:fontWeight,height: height,decoration: TextDecoration.none)
      ,textAlign: textAlign,maxLines: maxLines,softWrap: softWrap,overflow: overflow,);
  }

  static void callWhatsApp() {
    // var string = SpUtil.getString(Constant.whatsapp);
    // launchBrowserURL("https://api.whatsapp.com/send?phone="+(string??"")+"&text=hello");
  }
}

Future<T?> showElasticDialog<T>({
  required BuildContext context,
  bool barrierDismissible = true,
  required WidgetBuilder builder,
}) {
  return showGeneralDialog(
    context: context,
    pageBuilder: (BuildContext buildContext, Animation<double> animation,
        Animation<double> secondaryAnimation) {
      final Widget pageChild = Builder(builder: builder);
      return SafeArea(
        child: pageChild,
      );
    },
    barrierDismissible: barrierDismissible,
    barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
    barrierColor: Colors.black54,
    transitionDuration: const Duration(milliseconds: 550),
    transitionBuilder: _buildDialogTransitions,
  );
}

Widget _buildDialogTransitions(
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
    Widget child) {
  return FadeTransition(
    opacity: CurvedAnimation(
      parent: animation,
      curve: Curves.easeOut,
    ),
    child: SlideTransition(
      position: Tween<Offset>(begin: const Offset(0.0, 0.3), end: Offset.zero)
          .animate(CurvedAnimation(
        parent: animation,
        curve: const ElasticOutCurve(0.85),
        reverseCurve: Curves.easeOutBack,
      )),
      child: child,
    ),
  );
}

/// String 空安全处理
extension StringExtension on String? {
  String get nullSafe => this ?? '';
}
